import CommonWebSocket from '@/utils/websocket'
import { handleParamInUrl } from '@/utils/url'
import { conmmonWebSocketUrl } from '@/api/websocket'
import { notReaded } from '@/api/notify'
import { notify } from '@/utils/element'

const getDefaultState = () => {
  return {
    unReadMsg: null,
    ws: null
  }
}

const state = getDefaultState()

const mutations = {
  SET_UNREADMSG: (state, unReadMsg) => {
    state.unReadMsg = unReadMsg
  },
  SET_WEBSOCKET: (state, userId) => {
    // 如果已链接，直接返回
    if (state.ws) {
      return
    }
    // 进行连接
    state.ws = new CommonWebSocket({
      url: handleParamInUrl(conmmonWebSocketUrl, { userId: userId }),
      messageFun: async () => {
        const { data: { total, list } } = await notReaded(1, 100)
        let message
        switch (total) {
          // 无未读消息直接返回
          case 0:
            return
          // 只有一条未读消息则显示消息本身
          case 1:
            message = list[0].content
            break
          // 显示未读消息条数
          default:
            message = `您有${total === 100 ? '99+' : total}条未读消息`
            break
        }
        notify(message)
      }
    })
  },
  CLOSE_WEBSOCKET: (state) => {
    state.ws.close()
    state.ws = null
  }
}

const actions = {
  // 更新未读消息
  async updateUnRead ({ commit }, unReadMsg) {
    commit('SET_UNREADMSG', unReadMsg)
  },
  // 设置WebSocket
  async connect ({ commit }, userId) {
    commit('SET_WEBSOCKET', userId)
  },
  // 关闭WebSocket
  async close ({ commit }) {
    commit('CLOSE_WEBSOCKET')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
